import 'package:flutter/material.dart';
import '../../manger/network_utils.dart';
import '../../l10n/app_localizations.dart';
import '../view/login_thridlogin_view.dart';
import '../view/protocol_view.dart';
import '../../components/toast_utils.dart';
import '../view/protocol_dialog.dart';
import '../view/regis_input_view.dart';
import '../view/custom_text_field.dart';
import '../view/mobile_text_field.dart';
import '../view/ercode_text_field.dart';
import '../../models/user_info_model.dart';
import '../../manger/user_manger.dart';
import '../../components/custom_dialog.dart';
import '../controller/login_view.dart';
import '../../components/click_word_captcha.dart';
import '../../manger/qysdk_manger.dart';
import '../../manger/umevent_utils.dart';

class RegisCenterView extends StatefulWidget {
  final VoidCallback? onRegisterSuccess;
  const RegisCenterView({super.key, this.onRegisterSuccess});

  @override
  State<RegisCenterView> createState() => _RegisCenterViewViewState();
}

class _RegisCenterViewViewState extends State<RegisCenterView> {

  void _showLogoutDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => CustomDialog(
        title: AppLocalizations.of(context)!.emailsure,
        description: '${AppLocalizations.of(context)!.emailsureagain}${_usernameController.text}是否准确。' ,
        leftButtonText: AppLocalizations.of(context)!.cancel,
        rightButtonText: AppLocalizations.of(context)!.registerNow,
        onLeftPressed: () => Navigator.pop(context),
        onRightPressed: () {
          Navigator.pop(context);
          setState(() {
            confirm = 1;
          });
          regis();
        },
      ),
    );
  }
 
  @override
  void initState() {
    super.initState();
  }

  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _ercodeController = TextEditingController();
  final GlobalKey<ErcodeTextFieldState> _ercodeKey = GlobalKey();
  var regisType = 0;
  var ecode = '';
  var arcode = '1';
  var area = 'US';
  var confirm = 0;
  var captchaVerification = '';

  void regis() async {
    var params = {};
    if (regisType == 0) {
      UmengEvent.trackEvent("register_email_reg","邮箱注册","");
      params = {
        'email': _usernameController.text,
        'password': _passwordController.text,
        'code': _ercodeController.text,
        'confirm':confirm,
        'captchaVerification': captchaVerification,
      };
    } else {
      UmengEvent.trackEvent("register_phone_reg","手机号注册","");
      params = {
        'phone': _usernameController.text,
        'password': _passwordController.text,
        'countryCode': area,
        'areaCode': arcode,
        'code': _ercodeController.text,
        'captchaVerification': captchaVerification,
      };
    }
    ToastUtils.showLoadingToast(context);

    try {
      final response = await NetworkUtils.post(
        RequestCmd.register,
        body: params,
      );
      ToastUtils.dismissLoadingToast();
      final model = LoginModel.fromJson(response);
      if (model.code == 200) {
        if (model.data?.model != null) {
            final tokenModel = model.data!.model!;
            UserInfos.shared.saveToken(tokenModel.accessToken);
            regisType == 0 ? UmengEvent.trackEvent("register_email_success","邮箱注册成功","") : UmengEvent.trackEvent("register_phone_success","手机号注册成功","");
            widget.onRegisterSuccess?.call();
        } else if (model.data?.boolValue != null) {
          // 处理bool情况
          final boolValue = model.data!.boolValue!;
          if(boolValue && mounted){
            loadingClickWord(context,0);
          }
        }
      } else {
        if (response.toString().contains('201')) {
          setState(() {
            confirm = 0;
          });
          if (mounted) {
            _showLogoutDialog(context);
          }
        }
      }
    } catch (e) {
      print('Error fetching user info: $e');
    }
  }

  void sendCode() async {
    var params = {};
    if (regisType == 0) {
      params = {
        'email': _usernameController.text,
        'sendType': 1,
        'captchaVerification': captchaVerification,
      };
    } else {
      params = {
        'phone': _usernameController.text,
        'type': "2",
        'countryCode': area,
        'areaCode': arcode,
        'captchaVerification': captchaVerification,
      };
    }
    ToastUtils.showLoadingToast(context);

    try {
      final response = await NetworkUtils.post(
        regisType == 0 ? RequestCmd.sendEmailCode : RequestCmd.sendPhoneCode,
        body: params,
      );
      captchaVerification = "";

      ToastUtils.dismissLoadingToast();
      final model = PhoneCodeModel.fromJson(response);
      if (model.code == 200) {

        if (model.data?.boolValue != null) {
          // 处理bool情况
          final boolValue = model.data!.boolValue!;
          if(boolValue && mounted){
            loadingClickWord(context,1);
          }
        } else {
          ToastUtils.showCenterToast(context, model.msg ?? '发送成功');
          _ercodeKey.currentState?.startCountdown();
        }
      }else {
        ToastUtils.showCenterToast(context, model.msg ?? '注册失败,请联系客服');
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
    }
  }

  void loadingClickWord(BuildContext context,int type, {barrierDismissible = true}) {
    showDialog<Null>(
      context: context,
      barrierDismissible: barrierDismissible,
      builder: (BuildContext context) {
        return ClickWordCaptcha(
          onSuccess: (v){
            captchaVerification = v;
            if (type == 0) {
              regis();
            } else {
              sendCode();
            }
          },
          onFail: (){
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(15),
      child: Container(
        color: Colors.white, // 设置背景色为白色
        child: SizedBox(
          width: MediaQuery.of(context).size.width - 50,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              LoginThirdLoginView(type: 0,
              onThridLoginSuccess: () {
                widget.onRegisterSuccess?.call();
              }),
              Stack(
                children: [
                  RegisInputView(clickType: (type) {
                    setState(() {
                      regisType = type;
                    });
                  },),
                  Positioned(
                    top: 52, // RegisInputView高度60 - 8
                    left: 0,
                    right: 0,
                    child: Container(
                      height: 8,
                      color: Color(0xFFFFFFFF),
                      width: double.infinity,
                    ),
                  ),
                ],
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                child: regisType == 1
                    ? MobileTextField(
                        controller: _usernameController,
                        hintText: '${AppLocalizations.of(context)!.pleaseEnter}${AppLocalizations.of(context)!.phoneNumber}',
                        onChanged: (value) {},
                        onCodeValueChanged: (value) {
                          setState(() {
                            final parts = value.split(' ');
                            area = parts[0];
                            arcode = parts[1].startsWith('+') ? parts[1].substring(1) : parts[1];
                          });
                        },
                      )  
                    : CustomTextField(
                        controller: _usernameController,
                        hintText: '${AppLocalizations.of(context)!.pleaseEnter}${AppLocalizations.of(context)!.mailbox}',
                        onEditingComplete: () {
                          if (_usernameController.text.isNotEmpty && !_usernameController.text.contains('@')) {
                            setState(() {});
                          }
                        },
                        onChanged: (value) {},
                      ),
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 5),
                child: ErcodeTextField( 
                  key: _ercodeKey,
                  controller: _ercodeController,
                  onSendCode: (value) {                    
                    sendCode();
                  },
                  onChanged: (value) {
                },),
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                child: CustomTextField(
                  controller: _passwordController,
                  hintText: AppLocalizations.of(context)!.setThePassword,
                  obscureText: true,
                ),
              ),
              ProtocolView(),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Color(0xFF5D5FEE),
                    minimumSize: Size.fromHeight(50),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(22),
                    ),
                  ),
                  onPressed: () {
                    if (_usernameController.text.isEmpty){
                      ToastUtils.showCenterToast(context, '${AppLocalizations.of(context)!.pleaseEnter}${AppLocalizations.of(context)!.mailbox}/${AppLocalizations.of(context)!.phoneNumber}');
                      return;
                    }
                    if (_ercodeController.text.isEmpty){
                      ToastUtils.showCenterToast(context, '${AppLocalizations.of(context)!.pleaseEnter}${AppLocalizations.of(context)!.verificationCode}');
                      return;
                    }
                    if (_passwordController.text.isEmpty){
                      ToastUtils.showCenterToast(context, '${AppLocalizations.of(context)!.pleaseEnter}${AppLocalizations.of(context)!.password}');
                      return;
                    }
                    if (!ProtocolView.isSelected) {
                      showDialog(
                        context: context,
                        builder: (context) => ProtocolDialog(onCancel: () {
                          Navigator.pop(context);
                        },onSure: () {
                          setState(() {
                            ProtocolView.isSelected = true;
                            regis();
                          });
                        },),
                      );
                      return;
                    }
                    regis();
                  },
                  child: Text(
                    AppLocalizations.of(context)!.atRegister,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                    ),
                  ),
                ),
              ),        
              
              Stack(
                alignment: Alignment.center,
                children: [
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                    child: OutlinedButton(
                      style: OutlinedButton.styleFrom(
                        backgroundColor: Colors.white,
                        minimumSize: Size.fromHeight(50),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(22),
                        ),
                        side: BorderSide(
                          color: Color(0xFF5D5FEE),
                          width: 1,
                        ),
                      ),
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => LoginView(),
                          ),
                        );
                      },
                      child: Text(
                        AppLocalizations.of(context)!.login,
                        style: TextStyle(
                          color: Color(0xFF5D5FEE),
                          fontSize: 14,
                        ),
                      ),
                    ),
                  ),
                  Positioned(
                    right: 20,
                    top: 10 - 15,
                    child: Image.asset(
                      'assets/images/loginoriginal.png',
                      width: 180,
                      height: 34,
                    ),
                  ),
                ],
              ),
              Padding(
                padding: EdgeInsets.only(right: 15, bottom: 10),
                child: Align(
                  alignment: Alignment.center,
                  child: GestureDetector(
                    onTap: () {
                      QYSDK.showQYSession();
                    },
                    child: Text(
                      AppLocalizations.of(context)!.forgotPassword,
                      style: TextStyle(
                        fontSize: 13,
                        color: Color(0xFF666666),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}